package com.centerm.bluetooth.common.controller;

import android.content.Context;
import android.support.annotation.NonNull;

import com.centerm.bluetooth.common.Command;
import com.centerm.bluetooth.common.listener.ITerminalListener;
import com.centerm.bluetooth.common.model.Version;
import com.centerm.bluetooth.core.controller.BaseController;
import com.centerm.bluetooth.core.controller.constants.WaitEnum;
import com.centerm.bluetooth.ibridge.BluetoothIBridgeDevice;
import com.centerm.bluetooth.model.Respond;
import com.centerm.util.HexUtil;
import com.centerm.util.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by linwenhui on 2017/4/27.
 */

public class TerminalController extends BaseController<ITerminalListener> {

    private final static Map<byte[], String> productIdMap = new HashMap<>();

    static {
        productIdMap.put(new byte[]{0x00, 0x01}, "拉卡拉");
        productIdMap.put(new byte[]{0x00, 0x02}, "上海卡友");
        productIdMap.put(new byte[]{0x00, 0x03}, "江西中智");
        productIdMap.put(new byte[]{0x00, 0x04}, "CHINAPAY");
        productIdMap.put(new byte[]{0x00, 0x05}, "钱袋宝");
        productIdMap.put(new byte[]{0x00, 0x06}, "乐富支付");
    }

    private final static int VERSION = 0x01;
    private final static int RESET = 0x02;
    private final static int PSAM_TER = 0x03;
    private int type;

    public TerminalController(@NonNull Context context) {
        super((byte) 0x01,context);
    }

    public boolean getVersion() throws IOException {
        if (wait == WaitEnum.FREE) {
            type = VERSION;
            return send(Command.VERSION, null);
        }
        return false;
    }

    public boolean reset() throws IOException {
        type = RESET;
        boolean res = send(Command.RESET, null);
        if (res)
            setTimeoutTimer();
        return res;
    }

    public boolean getPSAMAndTerminalId() throws IOException {
        type = PSAM_TER;
        if (wait == WaitEnum.FREE) {
            boolean res = send(Command.PSAM_TERMINAL, null);
            if (res)
                setTimeoutTimer();
            return res;
        }
        return false;
    }

    @Override
    public void onDataReceived(BluetoothIBridgeDevice device, Respond respond) {
        super.onDataReceived(device, respond);
        switch (type) {
            case VERSION:
                parseVerion(respond);
                break;
            case RESET:
                parseReset();
                break;
            case PSAM_TER:
                parsePSAMAndTerminal(respond);
                break;
        }
        type = -1;
    }

    protected void parseVerion(Respond respond) {
        Logger.i(" == parseVerion == ");
        Version version = new Version();
        byte[] contents = respond.getContent();

        if (contents == null) {
            baseListener.onGetVersion(version);
            return;
        }

        //设备编号
        byte[] sn = new byte[20];
        System.arraycopy(contents, 0, sn, 0, 20);
        version.setSn(HexUtil.toASCII(sn));

        //硬件版本
        byte[] hardVer = new byte[2];
        System.arraycopy(contents, 21, hardVer, 0, 2);
        String hardVerString = HexUtil.byte2HexStr(hardVer);
        Logger.i(hardVerString);
        version.setHardVer(hardVerString.substring(0, 1) + "." + hardVerString.substring(1, 3) + " Build " + hardVerString.substring(3));

        //软件版本
        byte[] softVer = new byte[2];
        System.arraycopy(contents, 23, softVer, 0, 2);
        String softVerString = HexUtil.byte2HexStr(softVer);
        Logger.i(softVerString);
        version.setSoftVer(softVerString.substring(0, 1) + "." + softVerString.substring(1, 3) + " Build " + softVerString.substring(3));

        //密钥序列号（PSAM号）
        byte[] ksn = new byte[8];
        System.arraycopy(contents, 25, ksn, 0, 8);
        version.setKsn(HexUtil.byte2HexStr(ksn));

        //厂商自定义预留
        byte[] productId = new byte[2];
        System.arraycopy(contents, 33, productId, 0, 2);
        if (productIdMap.containsKey(productId)) {
            version.setProductId(productIdMap.get(productId));
        } else {
            version.setProductId("未知");
        }

        //厂商标识
        version.setProduct(contents[35] == 0x01 ? "C821E" : "未知");

        //硬件模块状态
        byte[] hardStatus = new byte[8];
        System.arraycopy(contents, 44, hardStatus, 0, 8);
        version.setHardStatus(HexUtil.byte2HexStr(hardStatus));

        //终端序列号
        byte[] terminal = new byte[32];
        System.arraycopy(contents, 52, terminal, 0, 32);
        version.setHardStatus(HexUtil.toASCII(terminal));

        //电压
        byte[] batteryLevel = new byte[2];
        System.arraycopy(contents, 84, batteryLevel, 0, 2);
        try {
            version.setBatteryLevel(Integer.valueOf(HexUtil.byte2HexStr(batteryLevel)));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        //电量
        version.setBatteryPercentage(contents[86]);

        //屏幕亮度
        version.setScreenLight(contents[87]);

        final boolean base = baseListener != null;
        Logger.i(base);
        if (base) {
            baseListener.onGetVersion(version);
        }

    }

    protected void parseReset() {
        Logger.i(" == parseReset ==");
        if (baseListener != null) {
            baseListener.onReset();
        }
    }

    protected void parsePSAMAndTerminal(Respond respond) {
        if (baseListener != null)
            baseListener.onGetPSAMAndTerminal(HexUtil.toASCII(respond.getContent()));
    }
}
